package com.hkbigdata.datagovernance.meta.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.dynamic.datasource.annotation.DS;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.hkbigdata.datagovernance.meta.bean.TableMetaInfo;
import com.hkbigdata.datagovernance.meta.bean.TableMetaInfoExtra;
import com.hkbigdata.datagovernance.meta.bean.TableMetaInfoForQuery;
import com.hkbigdata.datagovernance.meta.bean.TableMetaInfoVO;
import com.hkbigdata.datagovernance.meta.service.TableMetaInfoExtraService;
import com.hkbigdata.datagovernance.meta.service.TableMetaInfoService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.Date;
import java.util.List;

/**
 * <p>
 * 元数据表 前端控制器
 * </p>
 *
 * @author 
 * @since 2024-01-04
 */

@RestController
@RequestMapping("/tableMetaInfo")
public class TableMetaInfoController {
    @Autowired
    TableMetaInfoService tableMetaInfoService;

    @Autowired
    TableMetaInfoExtraService tableMetaInfoExtraService;

    @GetMapping("table-list")
    public String tablelist(TableMetaInfoForQuery tableMetaInfoForQuery) {
        List<TableMetaInfoVO> tableMetaInfoVOList = tableMetaInfoService.getTableMetaInfoList(tableMetaInfoForQuery);

        Integer total = tableMetaInfoService.getTableMetaInfoCount(tableMetaInfoForQuery);

        JSONObject jsonObject = new JSONObject();
        jsonObject.put("total", total);
        jsonObject.put("list", tableMetaInfoVOList);

        return jsonObject.toJSONString();
    }

        //手动更新元数据
        @PostMapping("/init-tables/{schemaName}/{assessDate}")
        public String initTables(@PathVariable("schemaName") String schemaName, @PathVariable("assessDate") String assessDate){
            tableMetaInfoService.initMetaInfo(assessDate,schemaName);
            return "success";

        }


        @GetMapping("/table/{id}")
        public String tabelDetail(@PathVariable("id") String id){
            //1.根据id查询到tableMetaInfo数据
            TableMetaInfo tableMetaInfo = tableMetaInfoService.getById(id);

            //2.再查询到这个tableMetaInfo对应的辅助信息数据
            TableMetaInfoExtra metaInfoExtra = tableMetaInfoExtraService.getOne((new QueryWrapper<TableMetaInfoExtra>().eq("schema_name",tableMetaInfo.getSchemaName()).eq("table_name",tableMetaInfo.getTableName())));

            //3.将辅助信息数据封装到TableMetaInfo对象中
            tableMetaInfo.setTableMetaInfoExtra(metaInfoExtra);

            //4.将数据转化为JSON字符串返回
            return JSON.toJSONString(tableMetaInfo);
        }

        @PostMapping("/tableExtra")
    public String updataTableExtra(@RequestBody TableMetaInfoExtra tableMetaInfoExtra){
        //设置更新时间
            tableMetaInfoExtra.setUpdateTime(new Date());
            tableMetaInfoExtraService.saveOrUpdate(tableMetaInfoExtra);
            return "success";
    }
}

